package com.ifnk.portaljava.dapWeb.socket;

/**
 * <p>Title: 处理数据包类</p>
 *
 * <p>Description: </p>
 *
 * <p>Copyright: Copyright (c) 2010</p>
 *
 * <p>Company: </p>
 *
 * @author WenSheng.Song.hlyt@gmail.com
 * @version 1.0
 */

import com.ifnk.portaljava.dapWeb.common.MessageBean;
import com.ifnk.portaljava.dapWeb.common.Util;
import com.ifnk.portaljava.dapWeb.dapweb.CDR;
import com.ifnk.portaljava.dapWeb.dapweb.Command;
import com.ifnk.portaljava.dapWeb.dataPacket.TypeDefine;
import flex.messaging.MessageBroker;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class PacketProcess extends Thread {
	
	private Log loger = LogFactory.getLog(PacketProcess.class);
	
	private SocketProperty sp;
	private ClientProperty cp;
	private byte[] packet;
	private Command command = new Command();
	private CDR cdrproccess = new CDR();
	int count = 0;
	int datacount = 0;

	public PacketProcess(ClientProperty cp, SocketProperty sp) {
		this.cp = cp;
		this.sp = sp;

	}

	public void run() {
		while (true) {
			if (cp.packets.isEmpty()) {
				count++;
				try {
					if (count > 4) {
						cp.process.remove(currentThread());
						//loger.debug("remove thread: " + this.getId());
						break;
					} else {
						Thread.sleep(100);
						continue;
					}
				} catch (Exception e) {
					Thread.currentThread().interrupt();
					loger.error("WebServer Exception " + e.toString());
					cp.process.remove(currentThread());
					e.printStackTrace();
					break;
				}
			} else {
				packet = (byte[]) cp.packets.poll();
			}
			// 包的类型
			if (packet == null)
				continue;
			processCdr(packet);
		}
	}
	
	public void processCdr(byte[] packet) {
		byte type = packet[4];
		int CMD = ((type & 0xf3) << 8) | packet[5];
		if ((CMD == TypeDefine.WWW_CT_START)
				|| (CMD == TypeDefine.WWW_CQ_START)) {
			command.DecodeStartCommand(packet);
			if (cp.getRequestDateFromProxyId().equals(
					command.getSessionId())) {
				// 肯定应答包
				if ((type & 0x08) == 0x08) {
					sp.flag = true;
					loger.info("WebServer Receive Definite Respond Packet");
				} else if ((type & 0x04) == 0x04) {// 否定应答包结束calltrace过程
					sp.flag = false;
					loger.info("WebServer Receive Negative Respond Packet");
					return;
				}
			}
		} else if ((CMD == TypeDefine.WWW_CT_STOP)
				|| (CMD == TypeDefine.WWW_CQ_STOP)) {
			command.DecodeStopCommand(packet);
			if (cp.getRequestDateFromProxyId().equals(
					command.getSessionId())) {
				cp.setKeepLiveTime(System.currentTimeMillis() / 1000);
					String subTopic = "KeepAlive" + cp.getClientId();
//					if (cp.packets.size() == 0)
//						loger.debug("the last packet");
					MessageBean bean = new MessageBean("本次过程已结束"+cp.getReceiveCdrCount(), true,
							false,cp.getReceiveCdrCount());
					MessageBroker messageBroker = MessageBroker
							.getMessageBroker(null);
					Util.routeMessage(messageBroker, subTopic, cp
							.getClientId(), bean);
				loger.info("WebServer Receive Stop Command Packet:"
						+ cp.getReceiveCdrCount());
			}
		} else if (CMD == TypeDefine.WWW_CT_CDRDATA
				|| CMD == TypeDefine.WWW_CQ_CDRDATA) {
			try {
				datacount++;
				command.DecodeCDRData(packet);
				if (cp.getRequestDateFromProxyId().equals(
						command.getSessionId())) {
					cp.setKeepLiveTime(System.currentTimeMillis() / 1000);
					cp.setKeepLive(true);
					String cdr = cdrproccess.proxCdrXmlToWwwCdrXml(cp
							.getReceiveCdrCount(), command.getCdr());
					cp.getData().add(cdr);
					sendToFlexThread();
				}
				packet = null;
			} catch (Exception e) {
				e.printStackTrace();
				loger.error("WebServer Exception " + e.toString());
				loger.error("WebServer CDR Exception cdr= "
						+ command.getCdr());
			}
		}
	}

	private void sendToFlexThread() {
		// 向页面发送数据

		if (cp.sendThreads.size() < 1) {
			for (int i = 0; i < 1 - cp.sendThreads.size(); i++) {
				SendDataToFlex send = new SendDataToFlex(cp);
				cp.add(send);
				send.start();
			}
		}
	}

	public byte[] getPacket() {
		return packet;
	}

	public void setPacket(byte[] packet) {
		this.packet = packet;
	}
}
